#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "ExtremeC_examples_chapter7_2_gun.h"

//属性结构
typedef struct {
    char* name;
    struct gun_t* gun;
} player_t;

//内存分配函数
player_t* player_new() {
    return (player_t*)malloc(sizeof(player_t));
}

//构造函数
void player_ctor(player_t* player, const char* name) {
    player->name = (char*)malloc(strlen(name + 1) * sizeof(char));
    strcpy(player->name, name);
    //如果不打算在构造函数中设置聚合指针，需要使其置空
    player->gun = NULL;
}

//析构函数
void player_dtor(player_t* player) {
    free(player->name);
}

//行为函数
void player_pickup_gun(player_t* player, struct gun_t* gun) {
    //在下行之后开始聚合关系
    player->gun = gun;
}

void player_shoot(player_t* player) {
    //我们需要检查玩家是否拿起了抢，否则射击毫无意义
    if (player->gun) {
        gun_trigger(player->gun);
    } else {
        printf("Player wants to shoot but he doesn't have a gun!");
        exit(1);
    }
}

void player_drop_gun(player_t* player) {
    //在下行之后两个对象之间的聚合关系结束。注意 gun 对象不应该被释放
    //因为与组合关系不同，player 对象不是 gun 对象的拥有者
    player->gun = NULL;
}

